var treeData;
$(document).ready(function () {

    // initFileInput("jobFile", "job/uploadJob.shtml");


    $.ajax({
        type: 'POST',
        async: false,
        url: 'repository/database/getSimpleList.shtml',
        data: {},
        success: function (data) {
            for (var i=0; i<data.length; i++){
                $("#jobRepositoryId").append('<option value="' + data[i].repositoryId + '">' + data[i].repositoryName + '</option>');
            }
        },
        error: function () {
            alert("请求失败！请刷新页面重试");
        },
        dataType: 'json'
    });
    $.ajax({
        type: 'POST',
        async: false,
        url: 'category/getSimpleList.shtml',
        data: {},
        success: function (data) {
            for (var i=0; i<data.length; i++){
                $("#categoryId").append('<option value="' + data[i].categoryId + '">' + data[i].categoryName + '</option>');
            }
        },
        error: function () {
            alert("请求失败！请刷新页面重试");
        },
        dataType: 'json'
    });
    $.ajax({
        type: 'POST',
        async: false,
        url: 'quartz/getSimpleList.shtml',
        data: {},
        success: function (data) {
            for (var i=0; i<data.length; i++){
                $("#jobQuartz").append('<option value="' + data[i].quartzId + '">' + data[i].quartzDescription + '</option>');
            }
        },
        error: function () {
            alert("请求失败！请刷新页面重试");
        },
        dataType: 'json'
    });
    // $("#customerQuarz").cronGen({
    // direction : 'left'
    // });
    reset();
});

var reset = function(){
    var jobId = $("#jobId").val();
    $.ajax({
        type: 'POST',
        async: false,
        url: 'job/getJob.shtml',
        data: {
            jobId : jobId
        },
        success: function (data) {

            var job = data.data;
            if (job.jobType === 2) {
                $(".jobRepository-div").remove();
                $(".jobPath-div").show();
            }
            if (job.jobType === 1) {
                $(".jobRepository-div").show();
                $(".jobPath-div").remove();
                loadRep(job.jobRepositoryId);
            }
            $("#jobRepositoryId").find("option[value=" + job.jobRepositoryId + "]").prop("selected",true);
            $("#jobPath").val(job.jobPath);
            $("#categoryId").find("option[value=" + job.categoryId + "]").prop("selected",true);
            $("#jobName").val(job.jobName);
            $("#jobQuartz").find("option[value=" + job.jobQuartz + "]").prop("selected",true);
            $("#jobLogLevel").find("option[value=" + job.jobLogLevel + "]").prop("selected",true);
            $("#jobDescription").val(job.jobDescription);
            $("#jobType").val(job.jobType);

            if (job.jobType == 2) {
                $(".file-caption-name").text(job.jobPath);
                $("#filePath").html(job.jobPath);

                var jobTransPathStr = job.jobTransPath;
                console.log(jobTransPathStr);
                var jobTransPath = JSON.parse(jobTransPathStr);
                // var jobTransPath=eval("(" + jobTransPathStr+ ")");
                console.log(jobTransPath);
                var divContent='';
                for (var i = 0;i<jobTransPath.length;i++){
                    divContent=divContent+'<span>'+jobTransPath[i]+'</span><br>';
                }
                $("#transFilesItems").html(divContent);
            }



        },
        error: function () {
            alert("请求失败！请刷新页面重试");
        },
        dataType: 'json'
    });
}

// $("#changeQuartz").click(function(){
// 	$("#default").toggle();
// 	$("#custom").toggle();
// 	$("#jobQuartz").val("");
// 	$("#customerQuarz").val("");
// });
$.validator.setDefaults({
    highlight: function (element) {
        $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
    },
    success: function (element) {
        element.closest('.form-group').removeClass('has-error').addClass('has-success');
    },
    errorElement: "span",
    errorPlacement: function (error, element) {
        if (element.is(":radio") || element.is(":checkbox")) {
            error.appendTo(element.parent().parent().parent());
        } else {
            error.appendTo(element.parent());
        }
    },
    errorClass: "help-block m-b-none",
    validClass: "help-block m-b-none"
});
$().ready(function () {
    var icon = "<i class='fa fa-times-circle'></i> ";
    $("#RepositoryJobForm").validate({
        rules: {
            jobName: {
                required: true,
                maxlength: 50
            },
            categoryId:{
                required: true
            },
            jobQuartz:{
                required: true
            },
            jobLogLevel: {
                required: true,
            },
            jobDescription: {
                maxlength: 500
            }
        },
        messages: {
            jobName: {
                required: icon + "请输入作业名称",
                maxlength: icon + "作业名称不能超过50个字符"
            },
            categoryId:{
                required: icon + "请选择作业分类"
            },
            jobQuartz:{
                required: icon + "请选择作业执行策略"
            },
            jobLogLevel: {
                required: icon + "请选择作业的日志记录级别",
            },
            jobDescription: {
                maxlength: icon + "作业描述不能超过500个字符"
            }
        },
        submitHandler:function(form){
            // $.post("job/update.shtml", decodeURIComponent($(form).serialize(),true), function(data){
            // 	var result = JSON.parse(data);
            // 	if(result.status == "success"){
            // 		layer.msg('更新成功',{
            // 			time: 2000,
            // 			icon: 6
            // 		});
            // 		setTimeout(function(){
            // 			location.href = "view/job/listUI.shtml";
            // 		},2000);
            // 	}else {
            // 		layer.msg(result.message, {icon: 2});
            // 	}
            // });
            var formData = new FormData(document.getElementById('RepositoryJobForm'));
            $.ajax({
                url:'job/update.shtml',
                data:formData,
                processData:false, //告诉jQuery不要去处理发送的数据
                contentType:false,// 告诉jQuery不要去设置Content-Type请求头
                type:'post',
                success:function (data) {
                    var result = JSON.parse(data);
                    if(result.status == "success"){
                        layer.msg('添加成功',{
                            time: 2000,
                            icon: 6
                        });
                        setTimeout(function(){
                            location.href = "view/job/listUI.shtml";
                        },2000);
                    }else {
                        layer.msg(result.message, {icon: 2});
                    }
                },
                error:function (e) {
                    console.log(e);
                }
            })
        }
    });


    $("#transFiles").on("change", function(event, files) {
        var files = document.getElementById("transFiles").files;
        var divContent='';
        var flag = 0;
        for (var i = 0; i < files.length; i++) {
            // divContent=divContent+'<input  id="filePath" name="jobFileName" value="'+files[i].name+'" /><span>'+files[i].name+'</span>';
            divContent=divContent+'<span>'+files[i].name+'</span><br/>';
            if (!/\.(ktr)$/.test(files[i].name)) {
                flag++;
            }
        }
        if (flag > 0) {
            alert("文件类型有误");
            //清除file
            $("#transFiles").val("");
            return false;
        }
        $("#transFilesItems").html(divContent);
    });
    $("#jobFile").on("change", function(event, files) {
        var filePath = document.getElementById("jobFile").value;
        console.log(filePath)
        if (!/\.(kjb)$/.test(filePath)) {
            alert("文件类型有误");
            //清除file
            $("#jobFile").val("");
            return false;
        }
        $("#filePath").html(filePath);
    });


    $("#jobRepositoryId").change(function(){
        loadRep($(this).val());

    });

    $("#jobPath").click(function(){
        var $jobRepositoryId = $("#jobRepositoryId").val();
        if (treeData != null){
            var index = layer.open({
                type: 1,
                title: '请选择作业',
                area: ["300px", '100%'],
                skin: 'layui-layer-rim',
                content: '<div id="repositoryTree"></div>'
            });
            $('#repositoryTree').jstree({
                'core': {
                    'data': treeData
                },
                'plugins' : ["search"]
            }).bind('select_node.jstree', function (event, data) {  //绑定的点击事件
                var jobNode = data.node;
                if (jobNode.icon == "none"){
                    var jobPath = "";
                    //证明是最子节点
                    for (var i = 0; i < treeData.length; i++){
                        if (treeData[i].id == jobNode.parent){
                            jobPath = treeData[i].path;
                        }
                    }
                    for (var i = 0; i < treeData.length; i++){
                        if (treeData[i].id == jobNode.id){
                            jobPath += "/" + treeData[i].text;
                        }
                    }
                    layer.close(index);
                    $("#jobPath").val(jobPath);
                }
            });
        }else if($jobRepositoryId != "" && treeData == null){
            layer.msg("请等待资源库加载");
        }else if($jobRepositoryId == ""){
            layer.msg("请先选择资源库");
        }
    });

});

var cancel = function(){
    location.href = "view/job/listUI.shtml";
}

//初始化fileinput控件（第一次初始化）
function initFileInput(ctrlName, uploadUrl) {
    var control = $('#' + ctrlName);
    control.fileinput({
        language: 'zh', //设置语言
        uploadUrl: uploadUrl, //上传的地址
        allowedFileExtensions: ['kjb'],//接收的文件后缀
        uploadAsync: true, //默认异步上传
        showUpload: false, //是否显示上传按钮
        showCaption: true,//是否显示标题
        dropZoneEnabled: false,//是否显示拖拽区域
        browseClass: "btn btn-primary", //按钮样式
        previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
    });
}
function loadRep(repositoryId) {
    if (repositoryId > 0){
        $.ajax({
            type: 'POST',
            async: false,
            url: 'repository/database/getJobTree.shtml',
            data: {
                repositoryId : repositoryId
            },
            success: function (data) {
                treeData = data;
            },
            error: function () {
                alert("请求失败！重新操作");
            },
            dataType: 'json'
        });
    }else{
        treeData = null;
    }
}